package fun.codedesign.jdk.lang.string;


import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;

public class CharCount {
    public static void main(String[] args) {
        String s = "hello world";
        System.out.println(s);

        Map<Character, Integer> map = new HashMap<Character, Integer>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int count = map.get(c) == null ? 1 : map.get(c) + 1;
            map.put(c, count);
        }
        System.out.println("排序前Map:" + map);

        Set<Entry<Character, Integer>> entry = map.entrySet();
        ArrayList<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>(entry);
        Collections.sort(list, new IntegerComparator());
        System.out.println("排序后的字段:" + list);

        for (Entry<Character, Integer> entry1 : list) {
            char c = entry1.getKey();
            int i = entry1.getValue();
            DecimalFormat f = new DecimalFormat("0.##%");
            System.out.println(c + "\t" + i + "\t" + f.format((double) i / s.length()));
        }
    }
}

class IntegerComparator implements Comparator<Entry<Character, Integer>> {
    public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
        return o2.getValue() - o1.getValue();
    }
}

